package com.store.store.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.store.store.entity.Dish;
import com.store.store.entity.DishFlavor;
import com.store.store.entity.dto.DishDto;
import com.store.store.mapper.DishMapper;
import com.store.store.service.DishFlavorService;
import com.store.store.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    DishFlavorService flavorService;

    /**
     * 新增菜品，同时插入菜品对应的口味数据，即对dish和dish_flavor操作
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表
        this.save(dishDto);

        Long dishId = dishDto.getId();  //菜品id

        for(DishFlavor i:dishDto.getFlavorList()){
            i.setDishId(dishId);
        }

        //保存菜品口味数据到菜品口味表
        flavorService.saveBatch(dishDto.getFlavorList());

    }

    /**
     * 根据id查询菜品信息和口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        //查询菜品基本信息
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //查询当前菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = flavorService.list(lambdaQueryWrapper);
        dishDto.setFlavorList(list);

        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新菜品的基本信息到菜品表
        this.updateById(dishDto);
        //清理当前菜品对应口味数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        flavorService.remove(queryWrapper);

        Long dishId = dishDto.getId();  //菜品id

        for(DishFlavor i:dishDto.getFlavorList()){
            i.setDishId(dishId);
        }

        //保存菜品口味数据到菜品口味表
        flavorService.saveBatch(dishDto.getFlavorList());
    }
}
